<template>
  <div>
    <!-- 条件搜索表单项 -->
    <div class="searchDiv">
      <div>
        <el-form-item label="角色名称">
          <el-input v-model="keyword" placeholder="角色名称" />
        </el-form-item>
      </div>
      <div style="margin: 10px;">
        <el-button type="primary" size="small" @click="fetchData">
          搜索
        </el-button>
        <el-button size="small" @click="handleReset">重置</el-button>
      </div>
      <!-- 添加按钮 -->
      <div class="tools-div">
        <hr />
        <el-button type="success" size="small" @click="addShow">
          添 加
        </el-button>
        <hr />
      </div>
    </div>
    <!-- 展示分页数据的表格 -->
    <div>
      <el-table :data="roles" stripe style="width: 100%">
        <el-table-column prop="roleName" label="角色名称" />
        <el-table-column prop="roleCode" label="角色Code" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" @click="editShow(scope.row)">
              修改
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
            <el-button @click="showAssignMenusDialog(scope.row)">
              分配菜单
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div>
        <!-- 添加角色表单对话框 -->
        <el-dialog v-model="dialogVisible" title="添加或修改角色" width="30%">
          <el-form label-width="120px">
            <el-form-item label="角色名称">
              <el-input v-model="role.roleName" />
            </el-form-item>
            <el-form-item label="角色Code">
              <el-input v-model="role.roleCode" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submit">提交</el-button>
              <el-button @click="dialogVisible = false">取消</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </div>
    </div>
    <div>
      <el-dialog v-model="assignMenusDialogFormVisible" title="分配菜单">
        <!-- 
            el-tree:用来展示树形数据的组件
            show-checkbox :展示每个节点前面的复选框
            node-key="id"：表示使用data中每个json的id属性值作为每个节点的key(后面展开、默认选中、获取tree选中节点时得到的都是key的值)
            props：表示tree的额外配置
        -->
        <el-tree
          ref="tree"
          :data="menus"
          show-checkbox
          node-key="id"
          :default-expand-all="true"
          :default-checked-keys="checkedMenuIds"
          :props="defaultProps"
        />
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="assignMenusDialogFormVisible = false">
              取消
            </el-button>
            <el-button type="primary" @click="handleAssignMenus">
              提交
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
    <!-- 分页导航 -->
    <div style="margin-top: 80px;">
      <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[1, 2, 3, 4, 5]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="fetchData"
        @current-change="fetchData"
      />
    </div>
  </div>
</template>

<script setup>
import {
  GetSysRolePage,
  DeleteRoleById,
  GetRoleById,
  UpdateRoleById,
  saveRole,
  GetMenuById,
  AssignMenus2Role,
} from '@/api/sysRole'
import { onMounted, ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

onMounted(() => {
  fetchData()
})

const roles = ref([])
const pageNum = ref(1)
const pageSize = ref(3)
const total = ref(0)
const keyword = ref('')
const dialogVisible = ref(false)
const role = ref({})
const assignMenusDialogFormVisible = ref(false)
const tree = ref({})
const menus = ref([
  {
    id: 1,
    createTime: '2023-05-04 10:46:47',
    updateTime: '2023-05-20 13:20:18',
    isDeleted: 0,
    parentId: 0,
    title: '系统管理',
    component: 'system',
    sortValue: 1,
    status: 1,
    children: [
      {
        id: 2,
        createTime: '2023-05-04 10:47:13',
        updateTime: '2023-11-06 07:21:04',
        isDeleted: 0,
        parentId: 1,
        title: '用户管理',
        component: 'sysUser',
        sortValue: 1,
        status: 1,
        children: [],
      },
      {
        id: 3,
        createTime: '2023-05-04 10:47:19',
        updateTime: '2023-05-06 17:33:58',
        isDeleted: 0,
        parentId: 1,
        title: '角色管理',
        component: 'sysRole',
        sortValue: 2,
        status: 1,
        children: [],
      },
      {
        id: 4,
        createTime: '2023-05-04 10:47:26',
        updateTime: '2023-05-06 17:33:58',
        isDeleted: 0,
        parentId: 1,
        title: '菜单管理',
        component: 'sysMenu',
        sortValue: 3,
        status: 1,
        children: [],
      },
      {
        id: 38,
        createTime: '2023-11-06 07:28:59',
        updateTime: '2023-11-06 07:28:59',
        isDeleted: 0,
        parentId: 1,
        title: '路径管理',
        component: 'sysPath',
        sortValue: 5,
        status: 0,
        children: [],
      },
    ],
  },
  {
    id: 21,
    createTime: '2023-05-20 14:03:11',
    updateTime: '2023-05-20 14:03:11',
    isDeleted: 0,
    parentId: 0,
    title: '数据管理',
    component: 'base',
    sortValue: 2,
    status: 1,
    children: [
      {
        id: 22,
        createTime: '2023-05-20 14:05:40',
        updateTime: '2023-05-20 14:05:40',
        isDeleted: 0,
        parentId: 21,
        title: '地区管理',
        component: 'region',
        sortValue: 1,
        status: 1,
        children: [],
      },
      {
        id: 23,
        createTime: '2023-05-20 14:06:04',
        updateTime: '2023-05-20 14:06:04',
        isDeleted: 0,
        parentId: 21,
        title: '商品单位',
        component: 'productUnit',
        sortValue: 2,
        status: 1,
        children: [],
      },
    ],
  },
  {
    id: 24,
    createTime: '2023-05-22 14:08:47',
    updateTime: '2023-05-22 14:08:47',
    isDeleted: 0,
    parentId: 0,
    title: '商品管理',
    component: 'product',
    sortValue: 3,
    status: 1,
    children: [
      {
        id: 25,
        createTime: '2023-05-22 14:09:00',
        updateTime: '2023-05-22 14:09:00',
        isDeleted: 0,
        parentId: 24,
        title: '分类管理',
        component: 'category',
        sortValue: 1,
        status: 1,
        children: [],
      },
      {
        id: 26,
        createTime: '2023-05-24 14:52:39',
        updateTime: '2023-05-24 14:52:39',
        isDeleted: 0,
        parentId: 24,
        title: '品牌管理',
        component: 'brand',
        sortValue: 2,
        status: 1,
        children: [],
      },
      {
        id: 27,
        createTime: '2023-05-25 02:38:09',
        updateTime: '2023-05-25 02:38:09',
        isDeleted: 0,
        parentId: 24,
        title: '分类品牌',
        component: 'categoryBrand',
        sortValue: 3,
        status: 1,
        children: [],
      },
      {
        id: 28,
        createTime: '2023-05-25 09:02:48',
        updateTime: '2023-05-25 09:02:48',
        isDeleted: 0,
        parentId: 24,
        title: '商品规格',
        component: 'productSpec',
        sortValue: 4,
        status: 1,
        children: [],
      },
      {
        id: 29,
        createTime: '2023-05-28 07:15:15',
        updateTime: '2023-05-28 07:15:15',
        isDeleted: 0,
        parentId: 24,
        title: '商品管理',
        component: 'product',
        sortValue: 5,
        status: 1,
        children: [],
      },
    ],
  },
  {
    id: 39,
    createTime: '2023-11-06 07:29:20',
    updateTime: '2023-11-06 07:29:20',
    isDeleted: 0,
    parentId: 0,
    title: '日志管理',
    component: 'log',
    sortValue: 4,
    status: 1,
    children: [
      {
        id: 40,
        createTime: '2023-11-06 07:29:41',
        updateTime: '2023-11-06 07:29:41',
        isDeleted: 0,
        parentId: 39,
        title: '订单日志管理',
        component: 'logOrder',
        sortValue: 1,
        status: 1,
        children: [],
      },
    ],
  },
])
const defaultProps = {
  children: 'children',
  label: 'title',
}
const checkedMenuIds = ref([1, 2, 3, 4, 22])

const addShow = () => {
  role.value = {}
  dialogVisible.value = true
}

const editShow = async row => {
  const { data } = await GetRoleById(row.id)
  role.value = data
  dialogVisible.value = true
}

const submit = async () => {
  if (role.value.id != null) {
    const { code } = await UpdateRoleById(role.value)
    if (code == 200) {
      dialogVisible.value = false
      ElMessage.success('修改成功')
      fetchData()
    }
  } else {
    const { code } = await saveRole(role.value)
    if (code == 200) {
      dialogVisible.value = false
      ElMessage.success('添加成功')
      fetchData()
    }
  }
}

const fetchData = async () => {
  const { code, message, data } = await GetSysRolePage(
    pageNum.value,
    pageSize.value,
    keyword.value
  )
  if (+code === 200) {
    console.log(data)
    roles.value = data.list
    total.value = data.total
  }
}

const handleReset = () => {
  pageNum.value = 1
  pageSize.value = 3
  keyword.value = ''
  fetchData()
}

const handleDelete = row => {
  ElMessageBox.confirm(
    `正在删除角色【${row.roleName}】 ,是否确认？`,
    'Warning',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const { code, message } = await DeleteRoleById(row.id)
      if (+code === 200) {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        //刷新页面数据
        fetchData()
      } else {
        ElMessage.error(message)
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
const showAssignMenusDialog = async row => {
  menus.value = []
  checkedMenuIds.value = []
  role.value = row
  const { data } = await GetMenuById(row.id)
  menus.value = data.menus
  console.log(data.menuIds)
  checkedMenuIds.value = data.menuIds
  assignMenusDialogFormVisible.value = true
}

const handleAssignMenus = async () => {
  //获取分配菜单对话框中选中的(半选和全选的)菜单id列表
  //  只有父菜单才有半选状态  无论父菜单半选还是全选 将来有该角色的用户登录时 都需要查询展示
  //调用树形控件tree的 方法可以获取选中的节点 或者节点的node-key列表
  // console.log(tree.value.getCheckedKeys(), tree.value.getHalfCheckedKeys())
  let menuIds = [
    ...tree.value.getCheckedKeys(),
    ...tree.value.getHalfCheckedKeys(),
  ]
  await AssignMenus2Role(role.value.id, menuIds)
  ElMessage.success('菜单分配成功')
  assignMenusDialogFormVisible.value = false
}
</script>
<style scoped>
.search-div {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}

.tools-div {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}
</style>
